#! /usr/bin/env python

"""
Create a tarball of the build results. The package command aggregates
the functionality of build, install and dist in a single command.

$ waf configure package

See also playground/distnet/ for a more enterprisey example
"""

APPNAME = 'ex'
VERSION = '1.0'

top = '.'

def configure(conf):
	pass

def build(bld):
	bld(rule='touch ${TGT}', target='foo.txt')
	bld.install_files('${PREFIX}/bin', 'foo.txt')

# ---------------------------

import shutil, os

from waflib import Build
class package_cls(Build.InstallContext):
	# to skip the installation phase (not recommended!):
	#    use "package_cls(Build.BuildContext)" instead of "package_cls(Build.InstallContext)",
	#    remove the "init_dirs" method
	#    change "self.tmp" to "self.bldnode"
	cmd = 'package'
	fun = 'build'

	def init_dirs(self, *k, **kw):
		super(package_cls, self).init_dirs(*k, **kw)
		self.tmp = self.bldnode.make_node('package_tmp_dir')
		try:
			shutil.rmtree(self.tmp.abspath())
		except:
			pass
		if os.path.exists(self.tmp.abspath()):
			self.fatal('Could not remove the temporary directory %r' % self.tmp)
		self.tmp.mkdir()
		self.options.destdir = self.tmp.abspath()

	def execute(self, *k, **kw):
		back = self.options.destdir
		try:
			super(package_cls, self).execute(*k, **kw)
		finally:
			self.options.destdir = back

		files = self.tmp.ant_glob('**')

		# we could mess with multiple inheritance but this is probably unnecessary
		from waflib import Scripting
		ctx = Scripting.Dist()
		ctx.arch_name = '%s%s-%s.tar.bz2' % (APPNAME, self.variant, VERSION) # if defined
		ctx.files = files
		ctx.tar_prefix = ''
		ctx.base_path = self.tmp
		ctx.archive()

		shutil.rmtree(self.tmp.abspath())

# for variants, add command subclasses "package_release", "package_debug", etc
def init(ctx):
	for x in ('release', 'debug'):
			class tmp(package_cls):
				cmd = 'package_' + x
				variant = x

